<template>
  <u-toast ref="uToast"></u-toast>
</template>
<script setup lang="ts">
import { onError, onHide, onLaunch, onShow } from "@dcloudio/uni-app";
import { getCurrentInstance, ref } from "vue";
import * as $httphome from "@/utlis/interface/home";
// #ifdef APP-PLUS
import APP_UPdata from "@/utlis/update";
import { NewOrder } from "@/Pinia/index";
import { initVoice, soundPlay } from "@/utlis/uni_api";

const fUN_AmapLocation = uni.requireNativePlugin("FUN-AmapLocation");
const timer: any = ref({});
let dateTimes = new Date().getTime();
// #endif
const { proxy } = getCurrentInstance() as any;

onLaunch(() => {
  // #ifdef APP-PLUS
  APP_UPdata(proxy); //   热更新检测

  setTimeout(() => {
    initVoice();
  }, 2500);

  keepAlive();
  // #endif
});

onShow(() => {
  console.log("App Show");
  // #ifdef APP-PLUS
  if (timer.value != null) {
    clearInterval(timer.value);
  }
  const { NewOrders } = NewOrder();

  //轮询接口，查询是否存在新的订单，并语音提示
  timer.value = setInterval(() => {
    //如果登录页闪动并报错未登录，说明token被保存，开发模式下清除应用数据，可能是运行其它应用到同一个hbuilder包下已经存储了token
    let accessToken = uni.getStorageSync("Authorization");
    //判断是否登录
    if (accessToken) {
      // console.log("查询是否存在新订单")
      // console.log("账号登录-查询是否有新的订单")
      $httphome
        .queryNewOrdersReuqest({ time: dateTimes }, proxy)
        .then(async (res: any) => {
          // console.log("res = " + JSON.stringify(res))
          dateTimes = res.data.time;
          let isNew = res.data.isNew;
          // console.log("新的订单", isNew);

          if (isNew) {
            NewOrders.order0 = res.data.order0;
            NewOrders.order1 = res.data.order1;
            // console.log("存在新订单")
            // #ifdef APP-PLUS
            await soundPlay(1);
            // #endif
          } else {
            let refundOrder = res.data.refundOrder;
            if (refundOrder > 0) {
              await soundPlay(2);
            }
            // console.log("没有新订单")
            NewOrders.order0 = 0;
            NewOrders.order1 = 0;
          }
        });
	  $httphome.infoCount(proxy).then(async (res: any) => {
		let isNew = res.data
		if (isNew) {
		 // #ifdef APP-PLUS
		  await soundPlay(9);
		  // #endif
		}  
	})
	
    } else {
      // console.log("账号未登录-无法查询新订单")
    }
  }, 5000);
  // #endif
});

onHide(() => {
  console.log("App Hide");
});

onError((err) => {
  console.log(err);
});

/**
 * 定位保活
 */
const keepAlive = () => {
  if (plus.os.name == "Android") {
    //屏幕唤醒
    fUN_AmapLocation.openWakeLock({ time: 5 }, function (result: any) {
      console.log(result);
    });
    fUN_AmapLocation.isIgnoringBatteryOptimizations(function (result: any) {
      //SDK>=23,否则返回不支持
      console.log(result);
      if (result && result.sdk_int >= 23) {
        if (!result.flag) {
          //申请电磁优化
          fUN_AmapLocation.requestIgnoreBatteryOptimizations(function (
            result: any
          ) {
            console.log(result);
          });
          //设置省电策略
          fUN_AmapLocation.setPowerKeeper(function (res: any) {
            console.log(res);
          });
        }
      }
    });

    fUN_AmapLocation.requestLocationPermissions(function (result: any) {
      console.log(result);
    });

    //设置自启动
    // fUN_AmapLocation.startToAutoStartSetting(function (result: any) {
    //   console.log(result)
    // });
    // fUN_AmapLocation.openGpsSetting((result:any) => {
    //   console.log('====fUN_AmapLocation定位====', JSON.stringify(result));
    // });

    // await fUN_AmapLocation.start(
    //     {
    //       intervalTime: 5000,
    //       reportInterval: 10,
    //       isReport: true,
    //       url: BaseUrl + '/riderLocationRecord/getRiderLocationRecord',
    //       params: {a: 1, B: '测试', c: true},
    //       headers: {a: '123', B: 'abcd', Authorization: "Bearer " + uni.getStorageSync('Authorization')},
    //       notificationTitle: "外卖狮骑手",
    //       notificationText: "外卖狮骑手后台运行中",
    //       isWifiActiveScan: true,
    //       apikey: "8044c96210279230199b20fd4defb06a"//高德key,配置不生效,需这里配置
    //     },
    //     function (result: any) {
    //       //见下方定位返回示例
    //       console.log('====fUN_AmapLocation定位====', JSON.stringify(result));
    //     }
    // );
  }
};
</script>

<style lang="scss" scoped>
@import "uview-plus/index.scss";
</style>
